package com.cyou.weplay.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * SysTimeManager
 *
 * @author zhaomingyu
 */
public class SysTimeManager {

    private static Logger logger = LoggerFactory.getLogger(SysTimeManager.class);

    private static long diffMillis = 0;

    public static void syncTime(long sampleTimeMillis) {
        diffMillis = sampleTimeMillis - System.currentTimeMillis();
    }

    /**
     * 获取当前系统时间
     *
     * @return 返回同步过的当前系统毫秒时间戳
     */
    public static long currentTimeMillis() {
        return System.currentTimeMillis() + diffMillis;
    }

    /**
     * 获取当前系统时间戳(秒)
     *
     * @return
     */
    public static long currentTimeSeconds() {
        return currentTimeMillis() / 1000;
    }

    public static void syncTime(Connection conn) throws SQLException {
        PreparedStatement ps = null;
        ResultSet rs = null;
        String time = "";
        try {
            ps = conn.prepareStatement("select concat(unix_timestamp(),'000') as time from dual");
            rs = ps.executeQuery();
            if (rs.next()) {
                time = rs.getString("time");
            }
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (conn != null) {
                conn.close();
            }
        }
        if (!"".equals(time)) {
            syncTime(Long.parseLong(time));
        }
    }
}
